package question;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Random;

/**
 * 问题5：抽奖箱抽奖
 *
 * @author 阳秋豪
 * @createTime 2024/3/12
 */
public class Test5 {
    /*有一个抽奖池,该抽奖池中存放了奖励的金额,该抽奖池中的奖项为
      {10,5,20,50,100,200,500,800,2,80,300,700};
      创建两个抽奖箱(线程)设置线程名称分别为“抽奖箱1"“抽奖箱2”
      随机从抽奖池中获取奖项元素并打印在控制台上,格式如下
      每次抽出一个奖项就打印一个(随机)
      抽奖箱1 又产生了一个 10 元大奖
      抽奖箱1 又产生了一个 800 元大奖
      抽奖箱2 又产生了一个 200 元大奖
      .....
    */
    public static void main(String[] args) {
        ArrayList<Integer> arrayList = new ArrayList<>();
        Collections.addAll(arrayList, 10, 5, 20, 50, 100, 200, 500, 800, 2, 80, 300, 700);
        QOneRunnable5 runnable = new QOneRunnable5(arrayList);
        Thread t1 = new Thread(runnable);
        Thread t2 = new Thread(runnable);
        t1.setName("抽奖箱1");
        t2.setName("抽奖箱2");
        t1.start();
        t2.start();
    }
}

class QOneRunnable5 implements Runnable {
    ArrayList<Integer> arrayList;
    Random random = new Random();

    public QOneRunnable5(ArrayList<Integer> arrayList) {
        this.arrayList = arrayList;
    }

    @Override
    public void run() {
        while (true) {
            synchronized (QOneRunnable5.class) {
                if (arrayList.isEmpty()) {
                    break;
                } else {
                    int i = random.nextInt(arrayList.size());
                    Integer remove = arrayList.remove(i);
                    System.out.println(Thread.currentThread().getName() + "又产生了一个 " + remove + "元大奖");
                }
            }
            try {
                Thread.sleep(10);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
    }
}